<template>
  <div class="column-chart">
    <div ref="chart" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch,inject } from 'vue';

const Echarts = inject('$echarts');

const props = defineProps({
  xAxisData: {
    type: Array,
    default: () => [],
  },
  seriesData: {
    type: Array,
    default: () => [],
  },
});

const chart = ref(null);
let myChart = null;

const initChart = () => {
  if (myChart) {
    myChart.dispose();
  }
  myChart = Echarts.init(chart.value);

  const option = {
    grid: {
      left: '1%',
      right: '0%',
      bottom: '0%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.xAxisData,
      axisLabel: {
        color: '#AAAAAA',
        fontSize: 12,
        // fontWeight: 'bold',
        interval: 0, // 强制显示所有标签
        formatter: function (value) {
          return value.replace(/(.{4})/g, '$1\n'); // 每4个字符换行
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#AAAAAA',
        fontSize: 16,
        // fontWeight: 'bold'
      },
      name: '(薪酬 元)',
      nameTextStyle: {
        color: '#AAAAAA',
        fontSize: 16,
        padding: [0, 40, 15, 0], // 调整名称位置
      },
    },
    series: [
      {
        data: props.seriesData,
        type: 'bar',
        barWidth: 28, // 固定柱子宽度为18px
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#589BFD',
              },
              {
                offset: 1,
                color: '#D4EAFF',
              },
            ],
          },
          borderRadius: [3, 3, 0, 0],
        },
        label: {
          show: true,
          position: 'top',
          formatter: '￥{c}',
          color: '#0169FF',
          fontSize: 16,
          // fontWeight: 'bold',
        },
      },
    ],
  };

  myChart.setOption(option);
};

watch(
  () => [props.xAxisData, props.seriesData],
  () => {
    initChart();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
});
</script>

<style scoped>
.column-chart {
  width: 100%;
  height: 100%;
}
</style>
